import React, { memo } from 'react';
import { notification, message } from 'antd';
import type { NotificationArgsProps } from 'antd';
import { 
  ExclamationCircleOutlined,
  CloseCircleOutlined,
  WarningOutlined,
  InfoCircleOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';

/**
 * 错误类型枚举
 */
export enum ErrorType {
  /** 网络错误 */
  NETWORK = 'network',
  /** 验证错误 */
  VALIDATION = 'validation',
  /** 权限错误 */
  PERMISSION = 'permission',
  /** 服务器错误 */
  SERVER = 'server',
  /** 业务逻辑错误 */
  BUSINESS = 'business',
  /** 未知错误 */
  UNKNOWN = 'unknown'
}

/**
 * 错误严重程度枚举
 */
export enum ErrorSeverity {
  /** 信息 */
  INFO = 'info',
  /** 警告 */
  WARNING = 'warning',
  /** 错误 */
  ERROR = 'error',
  /** 成功 */
  SUCCESS = 'success'
}

/**
 * 错误通知配置接口
 */
export interface IErrorNotificationConfig {
  /** 错误类型 */
  type?: ErrorType;
  /** 错误严重程度 */
  severity?: ErrorSeverity;
  /** 错误标题 */
  title?: string;
  /** 错误消息 */
  message: string;
  /** 错误描述 */
  description?: string;
  /** 显示时长（毫秒），0表示不自动关闭 */
  duration?: number;
  /** 是否显示关闭按钮 */
  closable?: boolean;
  /** 点击通知时的回调 */
  onClick?: () => void;
  /** 关闭通知时的回调 */
  onClose?: () => void;
  /** 额外的操作按钮 */
  btn?: React.ReactNode;
  /** 自定义图标 */
  icon?: React.ReactNode;
  /** 通知位置 */
  placement?: 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight';
  /** 是否使用简单消息模式 */
  useMessage?: boolean;
}

/**
 * 错误通知工具类
 */
class ErrorNotificationManager {
  private static instance: ErrorNotificationManager;
  
  private constructor() {
    // 配置全局通知样式
    notification.config({
      placement: 'topRight',
      duration: 4.5,
      rtl: false,
    });

    message.config({
      duration: 3,
      maxCount: 3,
    });
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): ErrorNotificationManager {
    if (!ErrorNotificationManager.instance) {
      ErrorNotificationManager.instance = new ErrorNotificationManager();
    }
    return ErrorNotificationManager.instance;
  }

  /**
   * 获取错误类型对应的图标
   */
  private getErrorIcon(type: ErrorType, severity: ErrorSeverity): React.ReactNode {
    switch (severity) {
      case ErrorSeverity.SUCCESS:
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case ErrorSeverity.INFO:
        return <InfoCircleOutlined style={{ color: '#1890ff' }} />;
      case ErrorSeverity.WARNING:
        return <WarningOutlined style={{ color: '#faad14' }} />;
      case ErrorSeverity.ERROR:
      default:
        switch (type) {
          case ErrorType.NETWORK:
            return <ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />;
          case ErrorType.PERMISSION:
            return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
          default:
            return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
        }
    }
  }

  /**
   * 获取错误类型对应的默认标题
   */
  private getDefaultTitle(type: ErrorType, severity: ErrorSeverity): string {
    if (severity === ErrorSeverity.SUCCESS) {
      return '操作成功';
    }

    switch (type) {
      case ErrorType.NETWORK:
        return '网络错误';
      case ErrorType.VALIDATION:
        return '数据验证失败';
      case ErrorType.PERMISSION:
        return '权限不足';
      case ErrorType.SERVER:
        return '服务器错误';
      case ErrorType.BUSINESS:
        return '业务处理失败';
      case ErrorType.UNKNOWN:
      default:
        return '系统错误';
    }
  }

  /**
   * 显示错误通知
   */
  public showError(config: IErrorNotificationConfig): void {
    const {
      type = ErrorType.UNKNOWN,
      severity = ErrorSeverity.ERROR,
      title,
      message: msg,
      description,
      duration = 4.5,
      closable = true,
      onClick,
      onClose,
      btn,
      icon,
      placement = 'topRight',
      useMessage = false
    } = config;

    const finalTitle = title || this.getDefaultTitle(type, severity);
    const finalIcon = icon || this.getErrorIcon(type, severity);

    if (useMessage) {
      // 使用简单消息模式
      const messageConfig: any = {
        content: msg,
        duration: duration,
        icon: finalIcon,
        onClose,
      };

      switch (severity) {
        case ErrorSeverity.SUCCESS:
          message.success(messageConfig);
          break;
        case ErrorSeverity.INFO:
          message.info(messageConfig);
          break;
        case ErrorSeverity.WARNING:
          message.warning(messageConfig);
          break;
        case ErrorSeverity.ERROR:
        default:
          message.error(messageConfig);
          break;
      }
    } else {
      // 使用详细通知模式
      const notificationConfig: NotificationArgsProps = {
        message: finalTitle,
        description: description || msg,
        icon: finalIcon,
        duration,
        closable,
        onClick,
        onClose,
        btn,
        placement,
      };

      switch (severity) {
        case ErrorSeverity.SUCCESS:
          notification.success(notificationConfig);
          break;
        case ErrorSeverity.INFO:
          notification.info(notificationConfig);
          break;
        case ErrorSeverity.WARNING:
          notification.warning(notificationConfig);
          break;
        case ErrorSeverity.ERROR:
        default:
          notification.error(notificationConfig);
          break;
      }
    }
  }

  /**
   * 显示网络错误
   */
  public showNetworkError(message: string, description?: string): void {
    this.showError({
      type: ErrorType.NETWORK,
      severity: ErrorSeverity.ERROR,
      message,
      description: description || '请检查网络连接后重试',
      duration: 5,
    });
  }

  /**
   * 显示验证错误
   */
  public showValidationError(message: string, description?: string): void {
    this.showError({
      type: ErrorType.VALIDATION,
      severity: ErrorSeverity.WARNING,
      message,
      description,
      useMessage: true,
    });
  }

  /**
   * 显示权限错误
   */
  public showPermissionError(message: string = '您没有权限执行此操作'): void {
    this.showError({
      type: ErrorType.PERMISSION,
      severity: ErrorSeverity.ERROR,
      message,
      description: '请联系管理员获取相应权限',
    });
  }

  /**
   * 显示服务器错误
   */
  public showServerError(message: string = '服务器内部错误'): void {
    this.showError({
      type: ErrorType.SERVER,
      severity: ErrorSeverity.ERROR,
      message,
      description: '服务暂时不可用，请稍后重试',
    });
  }

  /**
   * 显示业务错误
   */
  public showBusinessError(message: string, description?: string): void {
    this.showError({
      type: ErrorType.BUSINESS,
      severity: ErrorSeverity.WARNING,
      message,
      description,
    });
  }

  /**
   * 显示成功消息
   */
  public showSuccess(message: string, description?: string, useMessage: boolean = false): void {
    this.showError({
      severity: ErrorSeverity.SUCCESS,
      message,
      description,
      useMessage,
    });
  }

  /**
   * 显示信息消息
   */
  public showInfo(message: string, description?: string, useMessage: boolean = false): void {
    this.showError({
      severity: ErrorSeverity.INFO,
      message,
      description,
      useMessage,
    });
  }

  /**
   * 关闭所有通知
   */
  public closeAll(): void {
    notification.destroy();
    message.destroy();
  }

  /**
   * 关闭指定通知
   */
  public close(key: string): void {
    notification.destroy(key);
  }
}

/**
 * 错误通知组件
 * @description 提供全局错误通知功能的工具组件
 */
const ErrorNotification = memo(() => {
  // 这是一个工具组件，不需要渲染任何内容
  return null;
});

ErrorNotification.displayName = 'ErrorNotification';

// 导出单例实例
export const errorNotification = ErrorNotificationManager.getInstance();

export default ErrorNotification;